package com.example.rubbish;

import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.rubbish.DataBase.GDataBase;
import com.example.rubbish.DataBase.RDataBase;
import com.example.rubbish.DataBase.Record;
import com.example.rubbish.Fragment.RecordFragment;
import com.example.rubbish.Utils.JsonUtils;
import com.example.rubbish.Utils.ShareHelper;
import com.example.rubbish.Utils.SystemUiOperate;
import com.example.rubbish.Utils.okhttpUtils;
import com.example.rubbish.gson.GarbageInfo;
import com.example.rubbish.gson.Result;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ResultActivity extends AppCompatActivity {
    class Type {
        private static final int TYPE_TEXT = 0;
        private static  final int TYPE_PHOTO = 1;
    }
    private ImageView backButton;
    private TextView title_search;
    private TextView Text_cate;
    private TextView Text_garbage;
    private TextView Text_ps;
    private GDataBase db_info;
    private RDataBase db_record;
    private String searchContent ;
    private int searchType;

    private ImageButton button_speak;
    private TextToSpeech tts;
    private ImageView searchOffImage;
//    private LinearLayout searchView;

    private FloatingActionButton button_star;
    private boolean isFill=false;
    private GarbageInfo garbageInfo;

   private String cateName;
    private String garbageName;
    private String ps;


//    private float confidence;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SystemUiOperate.hide(getSupportActionBar(), getWindow());
        setContentView(R.layout.activity_result);

        title_search=findViewById(R.id.title_search);
        backButton= findViewById(R.id.back_to_search);
        //初始化语言播报的语言等
        initTTS();
        button_speak= findViewById(R.id.button_speak);

        //加载完数据前 白屏
        searchOffImage= findViewById(R.id.searchOffView);
        searchOffImage.setVisibility(View.VISIBLE);


        button_star=findViewById(R.id.button_star);

        Text_cate=findViewById(R.id.Cate_Name);
        Text_garbage=findViewById(R.id.Garbage_Name);
        Text_ps=findViewById(R.id.advise_content);
        db_info=GDataBase.getInstance(this);
        db_record=RDataBase.getInstance(this);

        //返回按钮
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        Intent intent=getIntent();

        searchType = intent.getIntExtra("searchType",-1);
        switch (searchType){
            case Type.TYPE_TEXT:
                //把文字搜索的内容放到标题栏中
                searchContent = intent.getStringExtra("searchContent");
                title_search.setText(searchContent);
                //到数据库中找，是否已查询过
                garbageInfo=db_info.getInfo(searchContent);
                //没有为null，有则不为空
                if(garbageInfo==null) {
                    Log.i("Result", "计费");
                    textRequestResult(searchContent);
                }
                if(garbageInfo!=null){
                    showResultInfo(garbageInfo);
                }

                break;
            case Type.TYPE_PHOTO:
                String bitMap = intent.getStringExtra("searchContent");
                photoRequestResult( bitMap );

                break;
            default:
                finish();
                break;
        }


        //根据 结果名是否在 记录 中存在判断是否已添加
        //按钮星星是否填充
        if(garbageInfo!=null && db_record.haveResult(garbageInfo.getGarbageName())){
            button_star.setImageResource(R.drawable.star_fill);
            isFill=true;
        }
        //收藏添加 和取消 ~ isFill
        button_star.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isFill){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //把result添加到record中
                            RecordFragment recordFragment = (RecordFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_record);
                            //得到当前日期并处理
                            Calendar calendar = Calendar.getInstance();
                            int year = calendar.get(Calendar.YEAR);
                            int month = calendar.get(Calendar.MONTH);
                            int day = calendar.get(Calendar.DAY_OF_MONTH);
                            StringBuilder monthBuilder = new StringBuilder();
                            if (month + 1 < 10) {
                                monthBuilder.append("0");
                            }
                            monthBuilder.append(month + 1);

                            StringBuilder dayBuilder = new StringBuilder();
                            if (day < 10) {
                                dayBuilder.append("0");
                            }
                            dayBuilder.append(day);
                            //添加到record
                            Record record = new Record();
                            record.setGarbageName(garbageInfo.garbageName);
                            record.setCateName(garbageInfo.getCateName());
                            record.setTime(year + "-" + monthBuilder + "-" + dayBuilder);
                            db_record.saveResult(record);
                            //提示添加成功
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ResultActivity.this, "添加成功", Toast.LENGTH_LONG).show();
                                    button_star.setImageResource(R.drawable.star_fill);
                                    isFill=true;
                                }
                            });

                        }
                    }).start();
                }else {//取消添加->从record中删除
                    String name = Text_garbage.getText().toString();
                    db_record.del(name);
                    Toast.makeText(ResultActivity.this, "取消添加", Toast.LENGTH_LONG).show();
                    button_star.setImageResource(R.drawable.star_null);
                    isFill=false;
                }


            }
        });

        button_speak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tts.setPitch(0.5f);
                tts.speak(garbageInfo.getGarbageName()
                        +garbageInfo.getCateName()+
                        "投放建议"+
                        garbageInfo.getPs()
                        ,TextToSpeech.QUEUE_FLUSH,null,null);


            }
        });



    }/* onCreate */

    private GarbageInfo photoRequestResult(String bitMap) {
        okhttpUtils.PhotoSearchRequest(bitMap,new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(ResultActivity.this,"访问失败，请稍后再试",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("Result","请求成功");
                final String responseText = response.body().string();
                Log.i("Result",responseText);
                final Result result = JsonUtils.handleInfoResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(result !=null && result.getStatus()==0) {
                            garbageInfo=result.getGarbageInfo();
                            //缓存response结果
                            saveInfo(garbageInfo);
                            //显示result
                            showResultInfo(garbageInfo);

                        }else {
                            //显示搜索失败图片
                            button_star.setVisibility(View.GONE);
                            button_speak.setClickable(false);
                            searchOffImage.setImageResource(R.drawable.search_off);
                        }

                    }//run()
                });//runOnUiThread


            }
        });

        return null;
    }


    @Override
    protected void onStop() {
        super.onStop();
        if(tts!= null) {
            //打断tts，关闭释放资源
            tts.stop();
            tts.shutdown();
        }
    }

    @Override
    protected void onDestroy() {
        if(tts!= null) {
            tts.stop();
            tts.shutdown();
            tts=null;
        }
        super.onDestroy();
    }

    private void initTTS() {
        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
                if(i==TextToSpeech.SUCCESS){
                    int result=tts.setLanguage(Locale.CHINA);
                    if(result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
                        Toast.makeText(ResultActivity.this,"语言播报失败",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void textRequestResult(String searchContent) {
        okhttpUtils.TextSearchRequest(searchContent, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ResultActivity.this,"访问失败，请稍后再试",Toast.LENGTH_LONG).show();
                    }
                });

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseText = response.body().string();
                final Result result = JsonUtils.handleInfoResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(result !=null && result.getStatus()==0) {
                            garbageInfo=result.getGarbageInfo();
                            //缓存response结果
                            saveInfo(garbageInfo);
                            //显示result
                            showResultInfo(garbageInfo);

                        }else {
                            button_speak.setClickable(false);
                            //显示搜索失败图片
                            button_star.setVisibility(View.GONE);
                            searchOffImage.setImageResource(R.drawable.search_off);
                        }

                    }//run()
                });//runOnUiThread
            }//onResponse()
        });//okhttpUtils.TextSearchRequest()
    }//requestResult(String searchContent)

    private void showResultInfo(GarbageInfo garbageInfo) {
        this.garbageInfo=garbageInfo;

        garbageName=garbageInfo.getGarbageName();
        cateName=garbageInfo.getCateName();
        ps=garbageInfo.getPs();
//        confidence=garbageInfo.getConfidence();


            //ui
        Text_cate.setText(cateName);
        Text_garbage.setText(garbageName);
        Text_ps.setText(ps);
        searchOffImage.setVisibility(View.GONE);
        AutoSpeak(garbageInfo);

    }

    private void AutoSpeak(GarbageInfo garbageInfo) {
        ShareHelper shareHelper = new ShareHelper(ResultActivity.this);
        boolean isAuto = shareHelper.getSettingSpeak();
        if(isAuto==true){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tts.setPitch(0.5f);
                    tts.speak(garbageInfo.getGarbageName()
                                    +garbageInfo.getCateName()+
                                    "投放建议"+
                                    garbageInfo.getPs()
                            ,TextToSpeech.QUEUE_FLUSH,null,null);
                }
            }).start();


        }

    }

    private void saveInfo(GarbageInfo garbageInfo) {

        db_info.saveGarbageInfo(garbageInfo);

    }


}